package com.netty.demo.server.netty.websocket;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author Administrator 余秀良
 * @version 1.0
 * <p>date: 2019年10月31日  10:37 </p>
 * <p>address: 四川成都 </p>
 */
@Component
public class NettyWebsocketServerInitializer extends ChannelInitializer<NioServerSocketChannel> {
    @Resource
    private NettyWebSocketHandler webSocketHandler;

    @Override
    protected void initChannel(NioServerSocketChannel ch) throws Exception {
        //设置log监听器，并且日志级别为debug，方便观察运行流程
        ch.pipeline().addLast("logging", new LoggingHandler("DEBUG"));
        //将请求与应答消息编码或者解码为HTTP消息
        ch.pipeline().addLast("http-codec", new HttpServerCodec());
        //HttpObjectAggregator的作用 将多个消息转换为单一的FullHttpRequest或者FullHttpResponse（将http消息的多个部分组合成一条完整的HTTP消息）
        ch.pipeline().addLast("aggregator", new HttpObjectAggregator(65536));
        //支持异步发送大的码流(大的文件传输),但不占用过多的内存，防止java内存溢出
        ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
        //进行设置心跳检测
        ch.pipeline().addLast(new IdleStateHandler(60, 30, 60 * 30, TimeUnit.SECONDS));
        //自定义的业务handler
        ch.pipeline().addLast("handler", webSocketHandler);
    }

}
